package com.cqjtu.eecs.service.impl;

import com.cqjtu.eecs.service.IFileTemplateService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @description: 文件模板下载服务类
 * @author: 徐文升
 * @create: 2022-03-10 11:19
 **/

@Service
public class FileTemplateService implements IFileTemplateService {

    public ResponseEntity<byte[]> excelTemplateExport(String fileName) throws IOException {
        String path = "/home/liyicai/opt/filetemp/" + fileName;

        FileInputStream fileInputStream = new FileInputStream(path);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = fileInputStream.read(buffer)) != -1){
            bos.write(buffer,0,len);
        }
        fileInputStream.close();
        bos.flush();
        byte[] bytes = bos.toByteArray();

        //设置ResponseEntity对象初始化所需要的Header
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentLength(bytes.length);

        //解决中文文件名不能识别的问题
        String encode = URLEncoder.encode(fileName, "UTF-8");
        httpHeaders.setContentDispositionFormData("attachment",encode);

        ResponseEntity responseEntity = new ResponseEntity(bytes,httpHeaders, HttpStatus.OK);
        return responseEntity;
    }
}
